package brickdestroyer.util;

import java.awt.*;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collection;
import javax.swing.ImageIcon;

/**
 * A class that loads images from files and performs the necessary event handling.
 */
final class ResourceTool {

    /**
     * This method loads an image from the specifed file location
     * within the jar file.
     * @param fileName image location within the jar file.
     * @return required image file.
     */
    public static Image loadImage(String fileName) {
        URL imageURL = ResourceTool.class.getResource(fileName);
        return (new ImageIcon(imageURL)).getImage();
    }

    /**
     * This method lists all the images in a give jar package resource
     * location.
     * @param pathname pathname in the current jar file
     * @return collection of files
     */
    public static Collection<File> listFilesInPackage(String pathname) {
        Collection<File> result = new ArrayList<File>();

        if (pathname.startsWith("/")) {
            pathname = pathname.substring(1);
        }

        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        if (classLoader == null) {
            return result;
        }

        URL resourceURL = classLoader.getResource(pathname);
        if (resourceURL == null) {
            return result;
        }

        File packageFile;
        try {
            packageFile = new File(URLDecoder.decode(resourceURL.getPath(), "UTF-8"));
        } catch (UnsupportedEncodingException ex) {
            return result;
        }
        if (packageFile == null || !packageFile.exists()) {
            return result;
        }

        for (File file : packageFile.listFiles()) {
            result.add(file);
        }
        return result;
    }

    /**
     * Constructor is private to prevent instantiation.
     */
    private ResourceTool() {
    }    
}
